import React from 'react';
import { message, Switch } from 'antd';
import errorMessage from 'share/errorMessage';
import debounce from 'lodash.debounce';
import Skeleton from 'components/skeleton';
import { messages } from 'share/common';
import invoiceManagementService from '../invoice-management.service';
import 'styles/supplier-management/invoice-management/invoice-check.scss';


class InvoiceCheck extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isInvoiceOwner: false,
      loading: true,
      buttonLoading: false,
      profile: {}
    };
    this.handleOnChange = debounce(this.handleOnChange, 300);
  }

  componentWillMount() {
    this.checkElectronic();
  };

  handleOnChange = (e) => {
    let { isInvoiceOwner, profile } = this.state;
    profile['invoice.owner.verify.enable'] = e;
    let params = {
      profileDetail: profile,
      entityOID: null,
      companyOID: null,
      entityType: '2003'
    };
    let chang = () => {
      invoiceManagementService.saveWechatInvoice(params)
        .then(() => {
          isInvoiceOwner = e;
          message.success(messages('common.operate.success'/*操作成功*/));
        })
        .catch((e) => {
          profile['invoice.owner.verify.enable'] = isInvoiceOwner;
          message.error(`${messages('common.operate.filed'/*操作失败*/)}，${e.response.data.message}`);
        })
        .finally(() => {
          this.setState({ isInvoiceOwner, profile, buttonLoading: false });
        });
    };
    this.setState({ buttonLoading: true }, chang);
  };

  //是否启用发票校验功能
  checkElectronic = () => {
    let { isInvoiceOwner, profile } = this.state;
    invoiceManagementService.getFunctionProfile()
      .then((res) => {
        profile = { ...res.data };
        isInvoiceOwner = !!res.data['invoice.owner.verify.enable'];
      })
      .catch(err => {
        errorMessage(err.response);
      })
      .finally(() => {
        this.setState({ isInvoiceOwner, profile, loading: false });
      });
  };

  render() {
    const { isInvoiceOwner, loading, buttonLoading } = this.state;
    return (
      <Skeleton loading={loading} title={false} paragraph={2}>
        <section className="invoice-check">
          <div className="invoice-check-label">
            {messages('supplier.key229')/*校验发票归属人一致性：*/}
          </div>
          <div className="invoice-check-value">
            <Switch
              loading={buttonLoading}
              checked={isInvoiceOwner}
              onChange={this.handleOnChange}/>
            <div className="invoice-check-desc">
              {messages('supplier.key230')/*开启之后，员工在发票控件录入归属人信息，系统会自动校验此发票与发票所关联的费用所属人是否一致，不一致则会打上“他人发票”标签。（费用归属人取值逻辑：优先取员工“身份证”的姓，若为空，则取员工姓名）*/}
            </div>
          </div>
        </section>
      </Skeleton>
    );
  }
}

export default InvoiceCheck;
